﻿using Enough.Lifecycle.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Popups;

namespace Enough.Lifecycle.Helper
{
    public static class MessageDialogHelper
    {
        private class EmailContext
        {
            public string ToAddress { get; set; }
            public string Subject { get; set; }
            public string MessageBody { get; set; }
        }

        /// <summary>
        /// Shows a message dialog
        /// </summary>
        /// <param name="message">the message</param>
        /// <param name="title">the optional title</param>
        /// <returns>this call is awaitable</returns>
        public static async Task ShowMessageDialogAsync(string message, string title = null, string labelOkText = null, string labelReportText = null, string reportToAddress = null, string reportSubject = null, string reportBody = null)
        {
            await UiThreadHelper.RunOnUiThread(async() => await showMessageDialogImplAsync(message, title, labelOkText, labelReportText, reportToAddress, reportSubject, reportBody));
       }

        /// <summary>
        /// Shows a message dialog
        /// </summary>
        /// <param name="message">the message</param>
        /// <param name="title">the optional title</param>
        /// <returns>this call is awaitable</returns>
        private static async Task showMessageDialogImplAsync(string message, string title = null, string labelOkText = null, string labelReportText = null, string reportToAddress = null, string reportSubject = null, string reportBody = null)
        {
            MessageDialog dialog = title == null ? new MessageDialog(message) : new MessageDialog(message, title);
            if (reportToAddress != null && labelOkText != null && labelReportText != null)
            {
                EmailContext context = new EmailContext { ToAddress = reportToAddress, Subject = reportSubject, MessageBody = reportBody };
                dialog.Commands.Add(new UIRelayCommand(processDialog, labelOkText));
                dialog.Commands.Add(new UIRelayCommand(processDialog, labelReportText, context));
                dialog.DefaultCommandIndex = 0;
            }
            try
            {
                await dialog.ShowAsync();
            }
            catch
            {
                // we cannot display several message dialogs at once
            }
        }

        private static async void processDialog(UIRelayCommand command)
        {
            EmailContext context = command.DataContext as EmailContext;
            if (context != null)
            {
                await EmailHelper.ComposeEmailAsync(context.ToAddress, subject: context.Subject, body: context.MessageBody);
            }
        }


    }
}
